package cn.usian.controller;

import cn.usian.common.R;
import cn.usian.dao.EmployeeMapper;
import cn.usian.entity.Employee;
import cn.usian.service.EmployeeService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestController
@RequestMapping("employee")
public class EmployeeController {
    @Resource
    private EmployeeService employeeService;


    @RequestMapping("login")
    public R<Employee> login(@RequestBody Employee employee, HttpServletRequest request){
        R<Employee> r=employeeService.selectOne(employee);
        //查看状态,1处于可用状态，否则为禁用
        if(r.getCode()!=1){
            return R.error("该用户处于禁用状态");
        }
        //登陆成功，id存入域，传到前台
        request.getSession().setAttribute("employee",r.getData().getId());
        return r;
    }

    @PostMapping("logout")
    public R logout(HttpServletRequest request){
        request.getSession().invalidate();
        return R.success("退出成功");
    }
    @GetMapping("page")
    public R page(@RequestParam(defaultValue = "1") Integer page,@RequestParam(defaultValue = "10")Integer pageSize,String name){
        Page<Employee> page1 = new Page<>(page,pageSize);
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        if(name !=null && name !=""){
            queryWrapper.like(Employee::getName,name);
        }
        Page<Employee>pages=employeeService.selectPage(page1,queryWrapper);
        return R.success(pages);
    }

    @PostMapping
    public R addEmp(@RequestBody Employee employee,HttpServletRequest request){
        long id=(long)request.getSession().getAttribute("employee");
        employee.setUpdateUser(id);
        employee.setCreateUser(id);
        employeeService.add(employee);
        return R.success("添加成功");
    }

    @GetMapping("{id}")
    public R findById(@PathVariable Long id){
        return employeeService.findById(id);
    }

   @PutMapping
    public R updateEmp(@RequestBody Employee employee){
        employeeService.updateEmp(employee);
        return R.success("修改成功");
   }


}
